import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Random;
import java.util.Scanner;
import java.util.Vector;

public class ClSrv {

	private Vector<Peer> peers;
	private InetAddress srvIP;
	private int srvPort;
	private Socket srvSock;
	private OutputStream outStream;
	private InputStream inStream;
	private PrintWriter out;
	private FileInputStream fStream;
	private File cfg;
	private Scanner sc;

	// @param config filename
	public ClSrv(String config) {
		try {
			String temp = new String();
			cfg = new File(config);
			fStream = new FileInputStream(cfg);
			sc = new Scanner(fStream);
			temp = sc.nextLine();
			srvIP = InetAddress.getByName(temp);
			temp = sc.nextLine();
			srvSock = new Socket(srvIP, Integer.parseInt(temp));
			temp = sc.nextLine();
			this.name = temp;
			sc.close();
			fStream.close();
			
			peers = new Vector<Peer>();

			try {
                Random rand = new Random(); 
                int port = rand.nextInt(60000)+1200;
				outStream = srvSock.getOutputStream();
				out = new PrintWriter(outStream, true);
				inStream = srvSock.getInputStream();
				Thread.sleep(1000);
				out.println(this.name);
				Thread.sleep(1000);
		        out.println("port;" + port);
		        Thread.sleep(1000);

				updatePeers();
				// ((SearchPanel)
				// Client.getMainFr().getMainPanel().getTabComponentAt(1)).getModel().setData(Object[][]
				// d = {getPeers().toArray(),{}});

				// inicjalizacja watku nasluchujacego (server)
				
				 Runnable srv = new ListenThread(port); 
				 Thread t = new Thread(srv); 
				 t.start();
				 
				
				

				System.out.println("po update");
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {

				// out.println("exit");
				// srvSock.close();
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void updatePeers() {
		peers.clear();
		out.println("list");
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		byte bytes[] = new byte[1000000];
		String line = new String(bytes);
		StringBuffer nejm = new StringBuffer(), IP = new StringBuffer(), size_str = new StringBuffer();
		StringBuffer filename = new StringBuffer(), token = new StringBuffer();
		StringBuffer port_str = new StringBuffer();
		int size = 0, peerIndex = 0, tagFlag = 0, filsFlag = 0, indIncFlag = 0, addFlag = 0;
		InetAddress ip;
		int port = 0;

		token = new StringBuffer();

		try {
			inStream.read(bytes);
			line = new String(bytes);
			//System.out.println(line);

			for (int i = 0; i < line.length(); i++) {
				if (line.charAt(i) == '[') {
					tagFlag = 1;
					token.delete(0, token.length());
				}

				if (i > 0 && line.charAt(i - 1) == ']') {
					tagFlag = 0;

				}

				if (tagFlag == 1 && line.charAt(i) != '['
						&& line.charAt(i) != ']') {
					token.append(line.charAt(i));
				}

				if (token.toString().compareTo("peer") == 0) {
					filsFlag = 0;
					indIncFlag = 0;

					if (line.charAt(i + 1) != ']' && line.charAt(i + 1) != '[')
						nejm.append(line.charAt(i + 1));

				}
				if (token.toString().compareTo("ipad") == 0) {
					if (line.charAt(i + 1) != ']' && line.charAt(i + 1) != '[')
						IP.append(line.charAt(i + 1));

				}
				if (token.toString().compareTo("port") == 0) {
					if (line.charAt(i + 1) != ']' && line.charAt(i + 1) != '[')
						port_str.append(line.charAt(i + 1));

				}
				if (token.toString().compareTo("fils") == 0) {
					if (filsFlag == 0) {
                        port = Integer.parseInt(port_str.toString());
						ip = InetAddress.getByName(IP.toString());
						Peer tmp = new Peer(nejm.toString(), ip, port);
						port_str.delete(0, port_str.length());
						peers.addElement(tmp);
						filsFlag = 1;
					}

				}
				if (token.toString().compareTo("filn") == 0) {
					addFlag = 0;
					if (line.charAt(i + 1) != ']' && line.charAt(i + 1) != '[')
						filename.append(line.charAt(i + 1));
				}

				if (token.toString().compareTo("size") == 0) {
					if (line.charAt(i + 1) != ']' && line.charAt(i + 1) != '[')
						size_str.append(line.charAt(i + 1));
				}

				if (token.toString().compareTo("endf") == 0) {
					if (addFlag == 0) {
						size = Integer.parseInt(size_str.toString());
						MyFile fajl = new MyFile(filename.toString(), size);

						peers.elementAt(peerIndex).getFiles().addElement(fajl);
						size_str.delete(0, size_str.length());
						filename.delete(0, filename.length());
						addFlag = 1;
					}
				}

				if (token.toString().compareTo("endd") == 0) {
					if (indIncFlag == 0) {
						peerIndex++;
						indIncFlag = 1;
					}
					nejm.delete(0, nejm.length());
					IP.delete(0, IP.length());
					size_str.delete(0, size_str.length());
					filename.delete(0, filename.length());
				}
				if (token.toString().compareTo("nopp") == 0)
					break;
			}
		} catch (IOException e) {

			System.out.println("cos nie teges?");
			e.printStackTrace();
		}

	}

	public Socket getSrvSock() {
		return srvSock;
	}

	public void setSrvSock(Socket srvSock) {
		this.srvSock = srvSock;
	}

	public PrintWriter getOut() {
		return out;
	}

	public void setOut(PrintWriter out) {
		this.out = out;
	}

	private String name;

	public Vector<Peer> getPeers() {
		return peers;
	}

	public void setPeers(Vector<Peer> peers) {
		this.peers = peers;
	}

	public InetAddress getSrvIP() {
		return srvIP;
	}

	public void setSrvIP(InetAddress srvIP) {
		this.srvIP = srvIP;
	}

	public int getSrvPort() {
		return srvPort;
	}

	public void setSrvPort(int srvPort) {
		this.srvPort = srvPort;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}
